import axios from 'axios';
import router from '../router/index';
import { getStorage, setStorage } from '../assets/js/storage';

let http = axios.create({
  baseURL: '/api', //ip后端还没确定http://192.168.2.229:8888  http://192.168.2.229:8100/zsdx
  timeout: 10000,
});
http.interceptors.request.use(req => {
  console.log(req);
  let token = getStorage('token');
  token && (req.headers['Authorization'] = token);
  if (token) req.headers['Authorization'] = `${token}`; /* 注意中间要加空格 */
  return req;
});

http.interceptors.response.use(
  resp => {
    resp.data.token && setStorage('token', resp.data.token);
    // console.log(resp);
    return resp;
  },
  error => {
    console.log(error);
    //这里代表响应报错
    let code = error.response.status;
    switch (code) {
      case 401:
        //401的错误要干的事情
        Element.Message('你的token过期了请重新登录');
        router.push('/login');
        return '401';
      case 500:
        // 500错误码要干的事情
        return '500';
    }
    return Promise.reject(error.response.data);
  }
);

export default http;
